package com.onecar.carplatform.common.utils;

import io.netty.buffer.ByteBuf;

/**
 * @Author : ljq
 * @Description : bcd 工具类
 * @Date : 2021/8/20 11:21
 * @Version : 1.0
 */
public class BcdUtil {
    public static String bcd2String(byte[] buf) {
        StringBuilder bcd = new StringBuilder();
        for (byte b : buf) {
            bcd.append(b >> 4 & 0x0f);
            bcd.append(b & 0x0f);
        }
        return bcd.toString();
    }

    public static String bcd2String(ByteBuf buf, int readNum) {
        StringBuilder bcd = new StringBuilder();
        for (int i = 0; i < readNum; i++) {
            byte aByte = buf.readByte();
            bcd.append(aByte >> 4 & 0x0f);
            bcd.append(aByte & 0x0f);
        }
        return bcd.toString();
    }

    public static byte[] string2Bcd(String buf, int maxLen, byte pad) {
        byte[] bytes = new byte[maxLen];
        char[] chars = buf.toCharArray();
        for (int i = 0, j = 0; i < maxLen; i++) {
            if (i < maxLen - buf.length() / 2)
                bytes[i] = pad;
            else {
                bytes[i] = (byte) (((chars[j++] & 0xf) << 4) | (chars[j++] & 0xf));
            }
        }
        return bytes;
    }
}
